package cn.pengpeng.demo;

import cn.pengpeng.domain.Order;
import cn.pengpeng.domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * Created by root on 2018/12/25.
 */
public class OrderCRUD {
    @Test
    public void insert(){
        try {
            //指定配置文件的路径(类路径)
            String resource = "mybatis-config.xml";
            //加载文件
            InputStream resourceAsStream = Resources.getResourceAsStream(resource);
            //创建会话工厂Builder,相当于连接池
            SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(resourceAsStream);
            //通过sf开启会话，相当于打开连接。
            SqlSession s = sf.openSession();

            User u = new User();
            u.setId(1);
            Order order = new Order();
            order.setOrderNo("100");
            order.setUser(u);

            s.insert("orders.insert",order);
            s.commit();
            s.close();

            System.out.println(s);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void selectOne(){
        try {
            //指定配置文件的路径(类路径)
            String resource = "mybatis-config.xml";
            //加载文件
            InputStream resourceAsStream = Resources.getResourceAsStream(resource);
            //创建会话工厂Builder,相当于连接池
            SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(resourceAsStream);
            //通过sf开启会话，相当于打开连接。
            SqlSession s = sf.openSession();

            Order o = s.selectOne("orders.selectOne", 1);
            System.out.println(o);
            s.commit();
            s.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void selectAll(){
        try {
            //指定配置文件的路径(类路径)
            String resource = "mybatis-config.xml";
            //加载文件
            InputStream resourceAsStream = Resources.getResourceAsStream(resource);
            //创建会话工厂Builder,相当于连接池
            SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(resourceAsStream);
            //通过sf开启会话，相当于打开连接。
            SqlSession s = sf.openSession();

            List<Order> list = s.selectList("orders.selectAll");
            for (Order order : list) {
                System.out.println(order);
            }

            s.commit();
            s.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
